package com.topteam.frame.entity.cms;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.ModelBean;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.topteam.frame.entity.FrameMenu;
import com.topteam.utility.StringUtil;

@ModelBean("CmsCategory")
public class CmsCategory extends Model<CmsCategory>{

	private static final long serialVersionUID = 2422520381863015435L;

	public static final CmsCategory dao = new CmsCategory();
	
	public Page<Record> getCmsCategoryPage(String code,int page,int size ){
		String sql = " from CmsCategory t where 1=1";
		if(StringUtil.isNotNull(code)){
			sql += " and t.code like '"+code+"%'";
		}
		sql += " order by t.order desc";
		return Db.paginate(page, size, "select t.* ", sql);
	}
	
	public String getNextCode(String parentId){
		String sql =null;
		String parentCode = "";
		if(StringUtil.isNull(parentId)){
			sql = "select max(code) from CmsCategory t where LENGTH(t.code)=4 ";
		}else{
			CmsCategory parent = findById(parentId);
			parentCode = parent.getStr("code");
			if(StringUtil.isNull(parentCode)){
				sql = "select max(code) from CmsCategory t where LENGTH(t.code)=4 ";
			}else{
				int length = parentCode.length();
				sql = "select max(code) from CmsCategory t where t.parentid = '"+parentId+"' AND LENGTH(t.code)="+(length+4)+" and substring(t.code,1,"+length+")='"+parentCode+"'";
			}
		}
		String code = Db.queryStr(sql);
		if(code == null){
			return parentCode+"0001";
		}else{
			return StringUtil.nextCode(code);
		}
	}
}
